package com.salim.leetcode.$30;

import java.util.*;
import java.util.stream.Collectors;

public class SubstringWithConcatenationOfAllWords {
    public List<Integer> findSubstring(String s, String[] words) {
        List<Integer> result = new ArrayList<>();
        if(words.length==0||s.length()==0){
            return result;
        }
        int startAt = 0;
        int length = words[0].length();
        List<String> tempWords = Arrays.stream(words).collect(Collectors.toList());
        for(int i=0;i<s.length();i++){
            if(i+length>s.length()){
                break;
            }
            String current = s.substring(i,i+length);
            if(tempWords.contains(current)){
                i = i+length-1;
                tempWords.remove(current);
                if(tempWords.isEmpty()){
                    result.add(startAt);
                    startAt +=1;
                    i = startAt -1;
                    tempWords = Arrays.stream(words).collect(Collectors.toList());
                }
            }else{
                startAt +=1;
                if(tempWords.size()<words.length){
                    i = startAt -1;
                    tempWords = Arrays.stream(words).collect(Collectors.toList());
                }
            }
        }
        return result;
    }

    public static void main(String[] args){
        SubstringWithConcatenationOfAllWords substringWithConcatenationOfAllWords = new SubstringWithConcatenationOfAllWords();
        String[] words = {"bar","foo","the"};
        System.out.println(substringWithConcatenationOfAllWords.findSubstring("barfoofoobarthefoobarman",words));
    }
}
